import axios from "axios";
import { message } from "antd";

const instance = axios.create({
  baseURL: "http://121.89.205.189:3000",
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    config.headers.token = localStorage.getItem("token");

    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (response.status === 200) {
      if (response.data.code === "200") {
        return response.data;
      } else if (response.data.code === "1001") {
        message.error("没有权限");
        sessionStorage.clear();
        return;
      } else {
        message.error(response.data.message);
        return;
      }
    } else if (response.status === 500) {
      message.error("服务端错误");
      return;
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const http = {
  get(url: string, params?: object) {
    return instance
      .get(url, {
        params: params,
      })
      .then((res) => {
        return res;
      });
  },
  post(url: string, data: object = {}) {
    return instance.post(url, data).then((res) => {
      return res;
    });
  },
};

export default http;
